#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include "csssp_common.h"
#include "csssp_mysql.h"

#define MYSQL_ERROR_LEN	512

static MYSQL * g_mysql;
extern unsigned int seq_num;

int cssp_mysql_get_seqnum(MYSQL *mysql)
{
	MYSQL_RES *result;
	MYSQL_ROW row;
	if (mysql_query(mysql, "select max(dt_seq) from detection_info_list;") != 0) {
		CSSP_ERROR("mysql init failure, Error[%u:%s]\n", mysql_errno(mysql), mysql_error(mysql));
		return -1;
	}
		
	result = mysql_store_result(mysql);
	if (result == NULL) {
		return -1;
	}

	row = mysql_fetch_row(result);
	if(row && *row) {
		seq_num = atoi(row[0]);
	}
	mysql_free_result(result);

	return 0;
}

int cssp_mysql_init(const char *host, const char *user, 
	const char *passwd, const char *db, unsigned int port, char * error)
{
	MYSQL * mysql = NULL;
	if (NULL == error) {
		return -1;
	}
	
	mysql = mysql_init(NULL);
	if (NULL == mysql) {
		CSSP_ERROR("mysql init failure, Error[%u:%s]\n", mysql_errno(mysql), mysql_error(mysql));
		goto ERROR;
	}
	
	if (!mysql_real_connect(mysql, host, user, passwd, db, port, NULL, 0)) {
		CSSP_ERROR("mysql_real_connect(), Error[%u:%s]\n", mysql_errno(mysql), mysql_error(mysql));
		goto ERROR;
	}

	if (mysql_query(mysql, "set names 'utf8';") != 0) {
		CSSP_ERROR("mysql ”set names 'utf8'“, Error[%u:%s]\n", mysql_errno(mysql), mysql_error(mysql));
		goto ERROR;
	}

	if (cssp_mysql_get_seqnum(mysql)) {
		goto ERROR;
	}
	g_mysql = mysql;

	CSSP_DEBUG("mysql [%s %s:%u] connect success [%p]\n", user, host, port, g_mysql);
	return 0;

ERROR:
	strncpy(error, mysql_error(mysql), MYSQL_ERROR_LEN);
	if (mysql) {
		mysql_close(mysql);
	}
	return -1;
}

int cssp_mysql_close()
{
	mysql_close(g_mysql);
  return 0;
}

int cssp_mysql_real_insert(const char * sql, unsigned int len)
{
	if (NULL == sql) {
		return -1;
	}
	
	if (mysql_real_query(g_mysql, sql, len) != 0) {
		CSSP_ERROR("mysql [%s], Error[%u:%s]\n", sql, mysql_errno(g_mysql), mysql_error(g_mysql));
		return -1;
	}

	CSSP_DEBUG("mysql: %s insert success\n\n", sql);
	return 0;
}

int cssp_mysql_insert(const char * sql)
{
	if (NULL == sql) {
		return -1;
	}
	
	if (mysql_query(g_mysql, sql) != 0) {
		CSSP_ERROR("mysql [%s], Error[%u:%s]\n", sql, mysql_errno(g_mysql), mysql_error(g_mysql));
		return -1;
	}

	CSSP_DEBUG("mysql: %s insert success\n\n", sql);
	return 0;
}

